/*
 * @Author: 刘柏麟
 * @Date: 2021-12-08 17:19:32
 * @LastEditors: 刘柏麟
 * @LastEditTime: 2021-12-08 19:09:57
 * @Description: file content
 */

import axios from 'axios'

import type { AxiosInstance } from 'axios'
import type { YZRequestInterceptors, YZRequestConfig } from './type'
import type { LoadingInstance } from 'element-plus/es/components/loading/src/loading'
import { ElLoading, ElMessage } from 'element-plus'

const DEFAULT_LOADING = true
class YZRequest {
  // 实例
  instance: AxiosInstance
  // 拦截器
  interceptors?: YZRequestInterceptors
  // 加载
  loading?: LoadingInstance
  // 是否显示加载
  showLoading: boolean
  constructor(config: YZRequestConfig) {
    // 创建实例
    this.instance = axios.create(config)
    // 加载(默认开启)
    this.showLoading = config.showLoading ?? DEFAULT_LOADING

    // 保存拦截器
    this.interceptors = config.interceptors
    // 请求拦截
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    )
    // 响应拦截
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    )
    // 添加所有的实例都有的拦截器
    this.instance.interceptors.request.use(
      (config) => {
        if (this.showLoading) {
          this.loading = ElLoading.service({
            lock: true,
            text: 'Loading',
            background: 'rgba(0, 0, 0, 0)'
          })
        }
        return config
      },
      (err) => {
        return err
      }
    )
    this.instance.interceptors.response.use(
      (res) => {
        const data = res.data

        if (data.code !== 0) return ElMessage.error(data.data)

        // switch (data.returnCode) {
        //   case '-1001':
        //     console.log('请求-1001')
        //     return
        // }
        this.loading?.close()
        return data
      },
      (err) => {
        this.loading?.close()
        // 例子:判断不同HttpErrorCode显示不同的错误信息
        console.log(`
        请求地址: ${err.response.request.responseURL}
        错误状态码 : ${err.response.request.status}
        错误信息: ${err.response.request.responseText}
        statusText:${err.response.statusText}
        `)
        err.response.status !== 200 && ElMessage.error(err.response.data)

        return err
      }
    )
  }

  request<T = any>(config: YZRequestConfig<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      // 是否显示loding
      if (config.showLoading === false) {
        this.showLoading = config.showLoading
      }
      // 单个请求对config的处理
      if (config.interceptors?.requestInterceptor) {
        config = config.interceptors.requestInterceptor(config)
      }

      this.instance
        .request<any, T>(config)
        .then((res) => {
          //单个请求对res的处理
          if (config.interceptors?.responseInterceptor) {
            res = config.interceptors.responseInterceptor(res)
          }
          resolve(res)

          // 将showLoading设置true,这样不会影响下一个请求
          this.showLoading = DEFAULT_LOADING
        })
        .catch((err) => {
          this.showLoading = DEFAULT_LOADING
          reject(err)
        })
    })
  }
  get<T = any>(config: YZRequestConfig<T>): Promise<T> {
    return this.request({ ...config, method: 'GET' })
  }
  post<T = any>(config: YZRequestConfig<T>): Promise<T> {
    return this.request({ ...config, method: 'POST' })
  }
  delete<T = any>(config: YZRequestConfig<T>): Promise<T> {
    return this.request({ ...config, method: 'DELETE' })
  }
  patch<T>(config: YZRequestConfig<T>): Promise<T> {
    return this.request({ ...config, method: 'PATCH' })
  }
}

export default YZRequest
